package internal

import (
	"fmt"
	"server/msg"
	"time"

	"github.com/name5566/leaf/gate"
)

type Player struct {
	Name   string      // 玩家名称
	Agent  *gate.Agent // 玩家的代理信息
	HBTime int64       // 上次心跳时间
}

type PlayerManager struct {
	Players map[string]*Player //map[string]*Player // 玩家列表
}

// 提供一个对外的世界管理模块句柄
var PlayerManagerObj *PlayerManager

func init() {
	PlayerManagerObj = &PlayerManager{}
	PlayerManagerObj.Players = make(map[string]*Player)
	go PlayerManagerObj.checkHeartbeat()
}

func (p *PlayerManager) AddPlayer(agent gate.Agent, username string) {
	//agent.SetUserData(name)
	fmt.Println("AddPlayer:", agent)
	newplayer := &Player{
		Name:  username,
		Agent: &agent,
	}
	p.Players[username] = newplayer

	p.BoardMessage(0, "system: ", "welcome "+username)
}

func (p *PlayerManager) BoardMessage(Msg_type int, Name string, Context string) {
	for _, player := range p.Players {
		(*player.Agent).WriteMsg(&msg.GC_game_ChatSend{
			Code:     0,        //接口状态 0代表成功：0 error,no news is good news
			Msg_type: Msg_type, //消息类型：0进入,1退出,2聊天
			Name:     Name,     //玩家名称
			Context:  Context,  //聊天内容
		})
	}

}

func (p *PlayerManager) RemovePlayer(name string) {

}

// 心跳检查，3秒一次
func (p *PlayerManager) checkHeartbeat() {
	for {
		var connectPlayers []*Player
		var leave_user string = ""
		time.Sleep(8 * time.Second)
		for _, player := range p.Players {
			second := time.Now().Unix() - player.HBTime
			if second > 10 {
				leave_user = leave_user + player.Name + " "
				(*p.Players[player.Name].Agent).Close()
			} else {
				// 保留满足条件的数据
				connectPlayers = append(connectPlayers, player)
			}

		}
		fmt.Println("checkHeartbeat", leave_user)
		if leave_user == "" {

		} else {
			// 将符合条件的玩家重新赋值给Players map
			p.Players = make(map[string]*Player)
			for _, player := range connectPlayers {
				p.Players[player.Name] = player
			}
			p.BoardMessage(1, "system: ", leave_user+" HB lost")
		}

		// p.Players.Range(func(key, value interface{}) bool {
		// 	p := value.(*Player)

		// 	second := time.Now().Unix() - p.HeartbeatTime
		// 	if p.RoomId <= 0 && second > 60 {
		// 		// 删除，并发送匹配失败消息
		// 		gm.players.Delete(key)
		// 		m := &msg.MatchCompleteBroadCast{MatchState: 0}
		// 		(*p.Agent).WriteMsg(m)

		// 	} else if p.RoomId > 0 && second > 10 {
		// 		// 删除，并发送删除玩家消息
		// 		gm.RemovePlayer(p.Name)
		// 	}

		// 	return true
		// })
	}
}

// 心跳
func (p *PlayerManager) Heartbeat(info *msg.CG_game_Heartbeat) {
	// 从玩家列表找到玩家
	var HB_name string = ""
	for _, player := range p.Players {
		if player.Name == info.Name {
			HB_name = player.Name
			break
		}
	}

	if HB_name == "" {
		return
	}
	p.Players[HB_name].HBTime = time.Now().Unix()

	(*p.Players[HB_name].Agent).WriteMsg(&msg.GC_game_Heartbeat{
		Name: HB_name, //玩家名称
	})
}
